package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.log.MyLog;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static net.sf.jsqlparser.parser.feature.Feature.set;
import static net.sf.jsqlparser.parser.feature.Feature.update;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> setmeal(Integer page, Integer pageSize, String name) {

        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        //模糊查询
        lqw.like(StringUtils.isNotEmpty(name), Setmeal::getName, name);
        //排序
        lqw.orderByDesc(Setmeal::getUpdateTime);
        //查询
        setmealService.page(pageInfo, lqw);
        Page<SetmealDto> resultPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, resultPage, "records");
        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> dtoArrayList = new ArrayList<>();
        for (Setmeal record : records) {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(record, setmealDto);
            Long categoryId = record.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                setmealDto.setCategoryName(category.getName());
            }
            dtoArrayList.add(setmealDto);
        }
        resultPage.setRecords(dtoArrayList);
        return R.success(resultPage);
    }

    /**
     * 添加套餐
     * @param setmealDto
     * @return
     */
    @PostMapping
    @MyLog("添加套餐")
    @CacheEvict(value ="setmeal" , allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功");
    }

    /**
     * 删除套餐
     * @param ids
     * @return
     */
    @DeleteMapping
    @MyLog("删除套餐")
    @CacheEvict(value ="setmeal" , allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids) {
        setmealService.detectByIds(ids);
        return R.success("删除成功");
    }

    /**
     * 利用id回显数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getById(@PathVariable Long id) {
        SetmealDto setmealDto = setmealService.getByIdDish(id);
        return R.success(setmealDto);
    }

    /**
     * 修改套餐
     *
     * @param setmealDto
     * @return
     */
    @PutMapping

    @CacheEvict(value ="setmeal" , allEntries = true)
    public R<String> update(@RequestBody SetmealDto setmealDto) {
        //更新setmeal表基本信息
        setmealService.updateById(setmealDto);

        //清理当前套餐对应的菜品   --setmeal_dish表的delete操作
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId, setmealDto.getId());
        setmealDishService.remove(lqw);

        //添加当前提交过来的菜品数据    --setmeal_dish表的insert操作
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
        return R.success("修改套餐完成");
    }

    /**
     * 修改状态
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")

    public R<String> status(@PathVariable Integer status, @RequestParam List<Long> ids) {
        for (Long id : ids) {
            Setmeal setmeal = setmealService.getById(id);
            setmeal.setStatus(status);
            setmealService.updateById(setmeal);
        }
        return R.success("修改成功");
    }

    /**
     * 移动端根据分类id查询套餐列表
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmeal" , key = "#setmeal.getCategoryId + '_' + #setmeal.getStatus")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        //select * from setmeal where categoryId = ?
        lqw.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        //查询status = 1 的
        lqw.eq(Setmeal::getStatus, setmeal.getStatus());
        //按修改时间倒序排列
        lqw.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> list = setmealService.list(lqw);
        return R.success(list);
    }

    /**
     * 移动端点击套餐图片显示
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    public R<List<Setmeal>> dish(@PathVariable Long id) {
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Setmeal::getId,id);
        List<Setmeal> setmealList = setmealService.list(lqw);
        return R.success(setmealList);
    }

}
